<template>
    <div class="search-div">
        <!-- 搜索表单 -->
        <el-form label-width="70px" size="small">
            <el-form-item label="角色名称">
                <el-input v-model="queryDto.roleName" style="width: 100%" placeholder="角色名称"></el-input>
            </el-form-item>
            <el-row style="display:flex">
                <el-button type="primary" size="small" @click="searchSysRole">
                    搜索
                </el-button>
                <el-button size="small" @click="resetData">重置</el-button>
            </el-row>
        </el-form>
    </div>


    <!-- 添加按钮 -->
    <div class="tools-div">
        <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>

    <!--- 角色表格数据 -->
    <el-table :data="list" style="width: 100%">
        <el-table-column prop="roleName" label="角色名称" width="180" />
        <el-table-column prop="roleCode" label="角色code" width="180" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" align="center" width="280" #default="scope">
            <el-button type="primary" size="small" @click="editShow(scope.row)">
                修改
            </el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row)">
                删除
            </el-button>
            <el-button type="warning" size="small" @click="showAssignMenu(scope.row)">
                分配菜单
            </el-button>
        </el-table-column>
    </el-table>

    <!--分页条-->
    <el-pagination v-model:current-page="pageParams.page" v-model:page-size="pageParams.limit"
        :page-sizes="[10, 20, 50, 100]" @size-change="fetchData" @current-change="fetchData"
        layout="total, sizes, prev, pager, next" :total="total" />


    <!-- 添加角色表单对话框 -->
    <el-dialog v-model="dialogVisible" title="添加或修改角色" width="30%">
        <el-form label-width="120px">
            <el-form-item label="角色名称">
                <el-input v-model="sysRole.roleName" />
            </el-form-item>
            <el-form-item label="角色Code">
                <el-input v-model="sysRole.roleCode" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


    <!-- 分配菜单的对话框  -->
    <el-dialog v-model="dialogMenuVisible" title="分配菜单" width="40%">
        <el-form label-width="80px">
            <el-tree ref="tree" :data="sysMenuTreeList" show-checkbox default-expand-all node-key="id" :props="defaultProps"
                :check-on-click-node="true" />
            <el-form-item>
                <el-button type="primary" @click="doAssign">提交</el-button>
                <el-button @click="dialogMenuVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { GetSysRoleListByPage, SaveSysRole, UpdateSysRole, DeleteSysRoleById,DoAssignMenuIdToSysRole } from '@/api/sysRole'
import { FindSysRoleMenuByRoleId } from '@/api/sysMenu';
import { ElMessage, ElMessageBox } from 'element-plus'

// 分页条总记录数
let total = ref(0)

// 定义表格数据模型
let list = ref([])

const queryDto = ref({ 'roleName': '' })

const pageParamsForm = {
    page: 1,
    limit: 2
}

const pageParams = ref(pageParamsForm)

const dialogVisible = ref(false)

const defaultForm = {
    id: '',
    roleCode: '',
    roleName: ''
}

const sysRole = ref(defaultForm)

const dialogMenuVisible = ref(false)

const sysMenuTreeList = ref([
    // {
    //     "id": 1,
    //     "title": "系统管理",
    //     "children":[
    //         {"id":2, "title": "用户管理" },
    //         {"id":3, "title": "角色管理" },
    //         {"id":4, "title": "菜单管理" }
    //     ]

    // },
    // {
    //     "id": 5,
    //     "title": "数据管理",
    //     "component": "base",
    //     "sortValue": 2,
    //     "status": 1,
    //     "createTime": "2023-05-04",
    //     "children":[
    //         {"id":6, "title": "商品单位" },
    //         {"id":7, "title": "地区管理" }
    //     ]
    // }
])

const defaultProps = {
    children: 'children',
    label: 'title'
}

const tree = ref()

let roleId = ref()

//-------------------------------------------------
onMounted(() => {
    fetchData()
})

const fetchData = async () => {
    const { code, message, data } = await GetSysRoleListByPage(pageParams.value.page, pageParams.value.limit, queryDto.value)
    list.value = data.list
    total.value = data.total
}

const searchSysRole = () => {
    fetchData()
}

const resetData = () => {
    queryDto.value.roleName = ''
    pageParams.value.page = 1
    fetchData()
}

const addShow = () => {
    dialogVisible.value = true
    sysRole.value = {}
}

const submit = async () => {

    if (sysRole.value.id) {
        const { code, message } = await UpdateSysRole(sysRole.value)
        if (code == 200) {
            dialogVisible.value = false
            ElMessage.success(message)
            fetchData()
        } else {
            ElMessage.error(message)
        }
    } else {
        const { code, message } = await SaveSysRole(sysRole.value)
        if (code == 200) {
            dialogVisible.value = false
            ElMessage.success(message)
            fetchData()
        } else {
            ElMessage.error(message)
        }
    }


}


const editShow = (row) => {
    sysRole.value = row
    dialogVisible.value = true
}


const deleteById = async (row) => {

    ElMessageBox.confirm('此操作将永久删除该数据，是否继续', "警告", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const { code } = await DeleteSysRoleById(row.id)
        if (code === 200) {
            ElMessage.success('删除成功')
            fetchData()
        }
    }).catch(() => {
        ElMessage.success('取消删除')
    })

    const { code } = await DeleteSysRoleById(row.id)
}


const showAssignMenu = async (row) => {
    dialogMenuVisible.value = true

    roleId.value = row.id

    const { data } = await FindSysRoleMenuByRoleId(row.id)

    sysMenuTreeList.value = data.sysMenuList

    tree.value.setCheckedKeys(data.roleMenuIds)

}

const doAssign = async () => {

    //1.获取选中的节点
    const checkedNods = tree.value.getCheckedNodes()
    const checkedNodesIds = checkedNods.map(node => {
        return {
            id: node.id,
            isHalf: 0
        }
    })

    //2.获取半选节点
    const halfCheckedNodes = tree.value.getHalfCheckedNodes()
    const halfCheckedNOdsIds = halfCheckedNodes.map(node =>{
        return {
            id: node.id,
            isHalf: 1
        }
    })

    //3.合并节点数据
    const menuIds = [...checkedNodesIds,...halfCheckedNOdsIds]

    console.log(menuIds)

    //4.构建请求数据
    const assignMenuDto = {
        roleId: roleId.value,
        menuIdList: menuIds
    }

    console.log(assignMenuDto)

    //5.发送请求
    const { code,message } = await DoAssignMenuIdToSysRole(assignMenuDto)

    //6.弹出消息并关闭对话框
    ElMessage.success('操作成功')
    dialogMenuVisible.value = false
}

</script>

<style scoped>
.search-div {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.tools-div {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}
</style>